package com.example.bgdharaniPlayer.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bgdharaniPlayer.R;
import com.example.bgdharaniPlayer.model.Playlist;
import com.example.bgdharaniPlayer.util.PlaylistStorage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 播放列表管理活动，用于创建、编辑、删除和选择播放列表
 */
public class PlaylistManagerActivity extends AppCompatActivity {

    private static final String TAG = "PlaylistManagerActivity";
    
    // UI组件
    private RecyclerView recyclerViewPlaylists;
    private Button btnAddPlaylist;
    private PlaylistAdapter adapter;
    
    // 数据
    private List<Playlist> playlists;

    //region 生命周期方法
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist_manager);
        initViews();
        setupListeners();
        setupItemTouchHelper();
        loadPlaylists();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadPlaylists();
    }
    //endregion

    //region 初始化和设置
    /**
     * 初始化视图组件
     */
    private void initViews() {
        recyclerViewPlaylists = findViewById(R.id.recyclerViewPlaylists);
        btnAddPlaylist = findViewById(R.id.btnAddPlaylist);

        // 设置RecyclerView
        recyclerViewPlaylists.setLayoutManager(new LinearLayoutManager(this));
        playlists = new ArrayList<>();
        adapter = new PlaylistAdapter(playlists, this::onPlaylistClick, this::onPlaylistDeleteClick);
        recyclerViewPlaylists.setAdapter(adapter);
    }

    /**
     * 设置事件监听器
     */
    private void setupListeners() {
        btnAddPlaylist.setOnClickListener(v -> showAddPlaylistDialog());
    }
    
    /**
     * 设置拖动排序功能
     */
    private void setupItemTouchHelper() {
        ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(
                ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
            
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, 
                                 @NonNull RecyclerView.ViewHolder viewHolder, 
                                 @NonNull RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                
                if (isValidPosition(fromPosition) && isValidPosition(toPosition)) {
                    movePlaylistItem(fromPosition, toPosition);
                    return true;
                }
                return false;
            }
            
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                // 不实现滑动删除功能
            }
            
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
                if (actionState == ItemTouchHelper.ACTION_STATE_DRAG && viewHolder != null) {
                    viewHolder.itemView.setAlpha(0.7f);
                }
            }
            
            @Override
            public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setAlpha(1.0f);
            }
        };
        
        new ItemTouchHelper(callback).attachToRecyclerView(recyclerViewPlaylists);
    }
    //endregion

    //region 数据操作
    /**
     * 加载所有播放列表
     */
    private void loadPlaylists() {
        Map<String, Playlist> playlistMap = PlaylistStorage.loadAllPlaylists(this);
        updatePlaylistsInUI(playlistMap);
        Log.d(TAG, "加载了 " + playlists.size() + " 个播放列表");
    }
    
    /**
     * 更新UI中的播放列表数据
     */
    private void updatePlaylistsInUI(Map<String, Playlist> playlistMap) {
        playlists.clear();
        playlists.addAll(playlistMap.values());
        
        // 按照order属性排序
        playlists.sort((p1, p2) -> Integer.compare(p1.getOrder(), p2.getOrder()));
        
        // 获取当前选中的播放列表ID并更新适配器
        String currentPlaylistId = PlaylistStorage.getCurrentPlaylistId(this);
        adapter.setCurrentPlaylistId(currentPlaylistId);
        adapter.notifyDataSetChanged();
    }
    
    /**
     * 移动播放列表项并保存顺序
     */
    private void movePlaylistItem(int fromPosition, int toPosition) {
        Playlist movedItem = playlists.remove(fromPosition);
        playlists.add(toPosition, movedItem);
        adapter.notifyItemMoved(fromPosition, toPosition);
        savePlaylistsOrder();
    }
    
    /**
     * 保存播放列表顺序
     */
    private void savePlaylistsOrder() {
        for (int i = 0; i < playlists.size(); i++) {
            Playlist playlist = playlists.get(i);
            playlist.setOrder(i);
            PlaylistStorage.savePlaylist(this, playlist);
        }
        Log.d(TAG, "保存播放列表顺序，共 " + playlists.size() + " 个播放列表");
    }
    
    /**
     * 检查位置是否有效
     */
    private boolean isValidPosition(int position) {
        return position >= 0 && position < playlists.size();
    }
    //endregion

    //region 用户交互
    /**
     * 显示添加播放列表对话框
     */
    private void showAddPlaylistDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_playlist, null);
        EditText etPlaylistName = dialogView.findViewById(R.id.etPlaylistName);
        Button btnSave = dialogView.findViewById(R.id.btnSave);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .create();

        btnSave.setOnClickListener(v -> {
            String name = etPlaylistName.getText().toString().trim();
            if (name.isEmpty()) {
                Toast.makeText(this, "播放列表名称不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 创建并保存新的播放列表
            PlaylistStorage.savePlaylist(this, new Playlist(name));
            loadPlaylists();
            dialog.dismiss();
        });

        btnCancel.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    /**
     * 显示编辑播放列表对话框
     */
    private void showEditPlaylistDialog(Playlist playlist) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_playlist, null);
        TextView tvTitle = dialogView.findViewById(R.id.tvDialogTitle);
        EditText etPlaylistName = dialogView.findViewById(R.id.etPlaylistName);
        Button btnSave = dialogView.findViewById(R.id.btnSave);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);

        tvTitle.setText("编辑播放列表");
        etPlaylistName.setText(playlist.getName());

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .create();

        btnSave.setOnClickListener(v -> {
            String name = etPlaylistName.getText().toString().trim();
            if (name.isEmpty()) {
                Toast.makeText(this, "播放列表名称不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 更新并保存播放列表
            playlist.setName(name);
            PlaylistStorage.savePlaylist(this, playlist);
            loadPlaylists();
            dialog.dismiss();
        });

        btnCancel.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }
    
    /**
     * 显示确认对话框
     */
    private void showConfirmationDialog(String title, String message, Runnable onConfirm) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", (dialog, which) -> onConfirm.run())
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 处理播放列表点击事件
     */
    private void onPlaylistClick(int position) {
        if (isValidPosition(position)) {
            Playlist playlist = playlists.get(position);
            Intent intent = new Intent(this, PlaylistActivity.class);
            intent.putExtra("playlist_id", playlist.getId());
            startActivity(intent);
        }
    }

    /**
     * 处理播放列表删除点击事件
     */
    private void onPlaylistDeleteClick(int position) {
        if (isValidPosition(position)) {
            Playlist playlist = playlists.get(position);
            showConfirmationDialog(
                "删除播放列表",
                "确定要删除播放列表 \"" + playlist.getName() + "\" 吗？",
                () -> {
                    PlaylistStorage.deletePlaylist(this, playlist.getId());
                    loadPlaylists();
                }
            );
        }
    }
    //endregion

    //region 适配器
    /**
     * 播放列表适配器
     */
    private static class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.ViewHolder> {
        
        // 回调接口
        interface OnPlaylistClickListener {
            void onPlaylistClick(int position);
        }
        
        interface OnPlaylistDeleteClickListener {
            void onPlaylistDeleteClick(int position);
        }
        
        // 数据和回调
        private final List<Playlist> playlists;
        private final OnPlaylistClickListener onPlaylistClickListener;
        private final OnPlaylistDeleteClickListener onPlaylistDeleteClickListener;
        private String currentPlaylistId;
        
        PlaylistAdapter(List<Playlist> playlists, 
                       OnPlaylistClickListener onPlaylistClickListener,
                       OnPlaylistDeleteClickListener onPlaylistDeleteClickListener) {
            this.playlists = playlists;
            this.onPlaylistClickListener = onPlaylistClickListener;
            this.onPlaylistDeleteClickListener = onPlaylistDeleteClickListener;
        }
        
        void setCurrentPlaylistId(String currentPlaylistId) {
            this.currentPlaylistId = currentPlaylistId;
        }
        
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_playlist, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Playlist playlist = playlists.get(position);
            
            // 设置文本和可见性
            holder.tvPlaylistName.setText(playlist.getName());
            holder.tvTrackCount.setText(playlist.size() + " 个音频");
            holder.tvCurrentMark.setVisibility(
                playlist.getId().equals(currentPlaylistId) ? View.VISIBLE : View.GONE
            );
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                if (onPlaylistClickListener != null) {
                    onPlaylistClickListener.onPlaylistClick(holder.getAdapterPosition());
                }
            });
            
            // 为播放列表名称单独设置点击事件
            holder.tvPlaylistName.setOnClickListener(v -> {
                if (onPlaylistClickListener != null) {
                    onPlaylistClickListener.onPlaylistClick(holder.getAdapterPosition());
                }
            });
            
            holder.btnDelete.setOnClickListener(v -> {
                if (onPlaylistDeleteClickListener != null) {
                    onPlaylistDeleteClickListener.onPlaylistDeleteClick(holder.getAdapterPosition());
                }
            });
        }
        
        @Override
        public int getItemCount() {
            return playlists.size();
        }
        
        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvPlaylistName;
            TextView tvTrackCount;
            TextView tvCurrentMark;
            ImageButton btnDelete;
            
            ViewHolder(View itemView) {
                super(itemView);
                tvPlaylistName = itemView.findViewById(R.id.tvPlaylistName);
                tvTrackCount = itemView.findViewById(R.id.tvTrackCount);
                tvCurrentMark = itemView.findViewById(R.id.tvCurrentMark);
                btnDelete = itemView.findViewById(R.id.btnDelete);
            }
        }
    }
    //endregion
}
